import sanitizeHtml from 'sanitize-html';
import { getEditorConfig } from '@/lib/editor/config';
import {
  handleCodeBlockHtml,
  handleImageHtml,
  handleTableHtml,
  handleTitleAnchor,
} from '@/lib/editor/handle';
import { restoreInitialData } from '@/lib/editor/restore';
import { composeMiddlewares } from '@/lib/tool';

export const initEditor = ({
  element,
  config,
  source,
}: {
  element: HTMLDivElement;
  config: any;
  source?: any;
}) => {
  // @ts-ignore
  const ckSource = source ?? CKSource;
  const watchdog = new ckSource.EditorWatchdog();
  const onReadyCallback: ({
    watchdog,
    editor,
  }: {
    watchdog: any;
    editor: any;
  }) => void = config.onReadyCallback;
  watchdog.setCreator((element: HTMLDivElement, config: any) =>
    ckSource.Editor.create(element, config).then((editor: any) => {
      onReadyCallback({ watchdog, editor });
      return editor;
    }),
  );
  watchdog.setDestructor((editor: any) => editor.destroy());
  watchdog.on('error', (e: any) => {
    console.error(e);
  });
  watchdog.create(element, getEditorConfig(config));
};

export const getEditorContentHtml = (editor: any, data?: any) => {
  if (!editor) {
    return '';
  }

  const value = data ?? editor.getData();
  if (!value) {
    return '';
  }

  const processHtml = composeMiddlewares(
    handleCodeBlockHtml,
    handleImageHtml,
    handleTitleAnchor,
    handleTableHtml,
  );
  const processedValue = processHtml(value.trim()) || '';
  return sanitizeHtml(processedValue, {
    allowedTags: false,
    allowedAttributes: false,
    allowVulnerableTags: true,
  });
};

export const setEditorContentHtml = (editor: any, value: any) => {
  if (!editor) {
    return;
  }
  editor.setData(restoreInitialData(value ?? ''));
};
